<template>
  <div class="body_detail page-miH page-bgBack">
    <a-row type="flex" justify="space-between" class="company">
      <a-col>
        <a-icon type="left" class="mg_r20" @click="$router.go(-1)" />
        <span v-if="!editor">添加账号</span>
      </a-col>
    </a-row>
    <div class="base_detail">基本信息</div>
    <a-form :form="form">
      <a-form-item :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }" label="账号姓名">
        <a-input v-decorator="['name', { rules: [{ required: true, message: '账号姓名必填' }] }]" :disabled="editor" placeholder="请输入" />
      </a-form-item>
      <a-form-item :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }" label="手机号码">
        <a-input
          v-decorator="[
            'phone',
            {
              rules: [
                { required: true, message: '手机号必填' },
                { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: '请输入11位手机号' }
              ]
            }
          ]"
          :max-length="11"
          style="width: 100%"
          :disabled="editor"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }" label="邮箱">
        <a-input
          v-decorator="[
            'email',
            {
              rules: [
                {
                  pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
                  message: '请输入正确的邮箱'
                }
              ]
            }
          ]"
          style="width: 100%"
          :disabled="editor"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item v-if="!this.$route.query.id" :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }" label="初始密码">
        <a-input
          v-decorator="['password', { rules: [{ required: true, message: '初始密码必填' }] }]"
          :disabled="disabled"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }" label="账号角色">
        <a-select
          v-decorator="['roleName', { rules: [{ required: true, message: '账号角色必填' }] }]"
          :disabled="disabled"
          style="width: 100%"
          @change="handleChange"
        >
          <a-select-option v-for="role in rolesList" :key="role.id" :value="role.id">{{ role.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }" label="是否游客模式">
        <a-switch
          v-model="isReadOnly"
          :disabled="disabled2 ? disabled2 : disabled"
          checked-children="是"
          un-checked-children="否"
          default-checked
          @change="onChange"
        />
        <a-tooltip placement="right" class="ml12">
          <template slot="title">
            <span>游客模式仅支持查看、下载数据不支持任何修改</span>
          </template>
          <a-icon type="question-circle" class="primarys" theme="filled" />
        </a-tooltip>
      </a-form-item>
      <a-form-item :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }" label="用工单位" class="ygdw">
        <a-switch
          v-model="choseEmp"
          :disabled="disabled2 ? disabled2 : disabled"
          checked-children="全部"
          un-checked-children="自选"
          default-checked
          @change="onChange"
        />
      </a-form-item>
      <a-form-item v-if="!choseEmp" :label-col="{ span: 3 }" :wrapper-col="{ span: 16 }" label="分管单位">
        <a-button @click="showModal">
          共{{ targetKeys.length }}个
          <a-icon type="right" />
        </a-button>
        <a-modal v-model="visible" title="选择分管单位" @ok="handleOk" width="800px">
          <a-transfer
            :list-style="{
              width: '320px',
              height: '400px'
            }"
            :operations="['添加', '删除']"
            :disabled="disabled"
            class="tree-transfer"
            :data-source="dataSource"
            :target-keys="targetKeys"
            :render="(item) => item.title"
            :show-select-all="false"
            @change="onTransChange"
            @search="onSeletChange"
            show-search
          >
            <!-- show-search -->
            <template slot="children" slot-scope="{ props: { direction, selectedKeys }, on: { itemSelect } }">
              <!-- {{ selectedKeys }} -->
              <a-tree
                :disabled="disabled"
                defaultExpandAll
                style="height: 300px; overflow-y: scroll"
                v-if="direction === 'left'"
                blockNode
                checkable
                checkStrictly
                :replaceFields="replaceFields"
                :checkedKeys="[...selectedKeys, ...targetKeys]"
                :tree-data="treeData"
                @check="
                  (_, props) => {
                    onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
                  }
                "
                @select="
                  (_, props) => {
                    onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
                  }
                "
              />
            </template>
          </a-transfer>
        </a-modal>
      </a-form-item>
    </a-form>
    <a-button v-if="!disabled" class="mg_l82" type="primary" @click="saveData">{{ editor ? "确认" : "添加确认" }}</a-button>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import { getByUserId, findCompanyGroup } from "./api";
export default {
  components: {},
  name: "AddAccountManagement",
  data() {
    return {
      treeData2: [],
      replaceFields: {
        children: "companyList",
        title: "name",
        key: "id",
        value: "id"
      },
      targetKeys: [],
      dataSource: [],
      choseEmp: true,
      allCompany: [],
      type: undefined,
      selectTreeId: "-1",
      siteName: undefined,
      employerIdList: [],
      childCompanyIdList: [],
      isAllChildCompany: false,
      form: this.$form.createForm(this, { name: "account" }),
      // 编辑
      editor: false,
      disabled: false,
      // 角色列表
      rolesList: [],
      disabled2: false,
      name: "",
      visible: false,
      copyDetail: {},
      siteId: undefined,
      detail: {
        hrRoleId: "",
        password: "",
        name: "",
        phone: "",
        isAllEmployer: true,
        employerIdList: []
      },
      selectedCityCodes: [],
      treeDatas: [],
      isReadOnly: false
    };
  },
  computed: {
    treeData: {
      get() {
        return this.treeData2;
      },
      set(val) {
        return handleTreeData(this.treeData2, this.targetKeys);
      }
    },
    ...mapGetters({ COMPANYLIST: "admin/COMPANYLIST" })
  },
  watch: {
    type(newValue) {
      console.log("debug log --> type", newValue);
    }
  },
  created() {
    this.findCompanyGroup(null, true);
    this.geRoles();
    this.editState();
    this.isReadOnly = this.$route.query.isReadOnly === "true";
  },
  mounted() {},
  methods: {
    onSeletChange(e, a, b) {
      // 根据搜索条件筛选
      this.findCompanyGroup(a);
    },
    showModal() {
      this.visible = true;
    },
    handleOk(e) {
      this.visible = false;
    },
    findCompanyGroup(value, v) {
      const data1 = {
        name: value || undefined
      };
      findCompanyGroup(data1)
        .then((res) => {
          this.treeData2 = this.addTreeSlot(res.data);
          if (this.treeData2[0] && this.treeData2[0].type === "site") {
            this.disabled2 = false;
          } else {
            this.disabled2 = true;
          }

          this.treeDatas = [];
          this.treeDatas = this.treeData2;
          if (v) {
            this.dataSource = [];
            this.flatten(this.treeData2);
          }
          if (this.editor && v) {
            this.detail = this.$route.query;
            this.getByUserId();
            this.copyDetail = { ...this.$route.query };
            if (!this.detail.employerIdList) {
              this.detail.employerIdList = [];
            }
          }
          if (this.editor) {
            const formKey = this.form.getFieldsValue();
            Object.keys(formKey).forEach((key) => {
              formKey[key] = this.detail[key];
            });
            this.form.setFieldsValue(formKey);
          }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    // 递归替换字段
    addTreeSlot(data) {
      if (!data) {
        return [];
      }
      data.forEach((el) => {
        if (el.type === "site") {
          el.disabled = true;
          el.key = "-1";
        } else {
          el.key = el.id;
        }
        el.title = el.name;

        this.addTreeSlot(el.companyList);
      });
      return data;
    },
    // 递归处理扁平数组
    flatten(list) {
      if (list !== null) {
        list.forEach((item) => {
          this.dataSource.push(item);
          this.flatten(item.companyList);
        });
      }
    },
    onTransChange(targetKeys) {
      this.targetKeys = targetKeys;
    },
    onChecked(_, e, checkedKeys, itemSelect) {
      const { eventKey } = e.node;
      itemSelect(eventKey, !isChecked(checkedKeys, eventKey));
    },
    editState() {
      this.editor = !!this.$route.query.id;
      setTimeout(() => {}, 100);
    },
    getByUserId() {
      getByUserId({
        userId: this.detail.id
      }).then((res) => {
        this.choseEmp = res.data.isAllChildCompany;
        if (res.data.groupIds) {
          this.targetKeys = res.data.companyIds.concat(res.data.groupIds);
        }
      });
    },
    // 选择用工单位
    onChange(e) {
      if (e) {
        this.detail.isAllEmployer = true;
        this.detail.isAllChildCompany = true;
        this.detail.employerIdList = [];
      } else {
        this.detail.isAllEmployer = false;
        this.detail.isAllChildCompany = false;
      }
    },
    // 编辑
    editorDetail() {
      this.disabled = !this.disabled;
      if (this.disabled) {
        history.back();
      }
    },
    // 删除账号
    deleteCount() {
      this.$confirm({
        title: "删除提示",
        content: "该操作将永久删除,确定删除该账号吗?",
        onOk: () => {
          this.$request({
            method: "POST",
            url: `/hr/api/v1/users/delete`,
            data: [this.$route.query.id]
          }).then(({ success }) => {
            if (success) {
              this.$notification["success"]({ message: "删除成功,返回列表" });
              history.back();
            }
          });
        }
      });
    },
    // 获取账号角色列表
    geRoles() {
      const params = { subjectType: "company" };
      if (this.$route.query.code) {
        params["code"] = this.$route.query.code;
      }
      this.$request({
        method: "GET",
        url: `/hr/api/v1/hrRoles/listAll`,
        params
      }).then(({ data }) => {
        this.rolesList = data;
      });
    },
    // 选择账号角色
    handleChange(e) {
      this.detail.hrRoleId = e;
    },
    // 新增/修改账号
    saveData() {
      this.form.validateFields((err, values) => {
        this.targetKeys.forEach((item, index) => {
          this.dataSource.forEach((item2, index2) => {
            if (item === item2.id && item2.type === "group") {
              this.childCompanyIdList.push(item);
            }
            if (item === item2.id && item2.type === "company") {
              this.employerIdList.push(item);
            }
          });
        });
        this.detail.isAllChildCompany = this.choseEmp;
        this.detail.childCompanyIdList = this.childCompanyIdList;
        this.detail.employerIdList = this.employerIdList;
        this.detail.isReadOnly = this.isReadOnly;
        Object.keys(values).forEach((key) => {
          this.detail[key] = values[key];
        });
        if (!err) {
          if (this.editor) {
            this.detail.userId = this.detail.id;
            this.$request({
              method: "POST",
              url: `/hr/api/v1/users/updateRole`,
              data: this.detail
            }).then(({ success }) => {
              if (success) {
                this.$notification["success"]({ message: "修改成功" });
                history.back();
              }
            });
          } else {
            this.$request({
              method: "POST",
              url: `/hr/api/v1/users/save`,
              data: this.detail
            }).then(({ success }) => {
              if (success) {
                this.$notification["success"]({ message: "新增成功" });
                history.back();
              }
            });
          }
        }
      });
    }
  }
};
function isChecked(selectedKeys, eventKey) {
  return selectedKeys.indexOf(eventKey) !== -1;
}

function handleTreeData(data, targetKeys = []) {
  data.forEach((item) => {
    item["disabled"] = targetKeys.includes(item.key);
    if (item.children) {
      handleTreeData(item.children, targetKeys);
    }
  });
  return data;
}
</script>
<style lang="scss" scoped>
.tree-transfer .ant-transfer-list:first-child {
  width: 50%;
  flex: none;
  >>> .ant-transfer-list-body-search-wrapper {
    display: none;
  }
}
.body_detail {
  padding: 24px;
  .company {
    color: #333333;
    font-size: 16px;
    // margin: 20px 0;
  }
  .base_detail {
    height: 48px;
    line-height: 48px;
    padding-left: 24px;
    margin: 20px 0;
    background: rgba(250, 250, 250, 1);
  }
}
.ygdw {
  ::v-deep.ant-switch {
    background: var(--primary);
  }
}
</style>
<style lang="scss">
.tree-transfer {
  .ant-transfer-list:nth-child(3) {
    .ant-transfer-list-body-search-wrapper {
      display: none;
    }
  }
}
</style>
